package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import com.google.android.material.switchmaterial.SwitchMaterial;


public class SettingsActivity extends AppCompatActivity {
    private SwitchMaterial switchAdminMode;
    private LinearLayout layoutAddArticle, layoutAddProduct;
    private Button btnLogout, btnAddAccount;
    private RecyclerView recyclerViewAccounts;
    private AccountAdapter accountAdapter;
    private List<Account> accountList;
    private DatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        dbHelper = new DatabaseHelper(this);
        initViews();
        setupAccountRecyclerView();
        setupAdminModeSwitch();
        setupClickListeners();
    }

    private void initViews() {

          switchAdminMode = findViewById(R.id.switch_admin_mode);

        switchAdminMode = findViewById(R.id.switch_admin_mode);

        layoutAddArticle = findViewById(R.id.activity_add_article);
        layoutAddProduct = findViewById(R.id.activity_add_product);
        btnLogout = findViewById(R.id.btn_logout);
        btnAddAccount = findViewById(R.id.btn_add_account);
        recyclerViewAccounts = findViewById(R.id.recycler_view_accounts);
    }


    private void setupAccountRecyclerView() {
        accountList = convertUsersToAccounts(dbHelper.getAllUsers());
        accountAdapter = new AccountAdapter(accountList);

        accountAdapter.setOnItemClickListener(account ->
                showChangePasswordDialog(account.getId())
        );

        accountAdapter.setOnItemLongClickListener(account ->
                showDeleteAccountDialog(account.getId())
        );

        recyclerViewAccounts.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewAccounts.setAdapter(accountAdapter);
    }

    private void setupAdminModeSwitch() {
        // 根据当前用户权限设置开关状态
        boolean isAdmin = checkAdminStatus(); // 需要实现这个方法
        switchAdminMode.setChecked(isAdmin);


        switchAdminMode.setOnCheckedChangeListener((buttonView, isChecked) -> {
            toggleAdminOptions(isChecked);
            // 这里可以保存管理员状态到SharedPreferences
        });
    }

    private void toggleAdminOptions(boolean show) {
        LinearLayout adminFunctionsLayout = findViewById(R.id.layout_admin_functions);
        if (adminFunctionsLayout != null) {
            adminFunctionsLayout.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    private void setupClickListeners() {
        // 添加账号
        btnAddAccount.setOnClickListener(v ->
                startActivity(new Intent(this, RegisterActivity.class))
        );

        // 添加文章
        layoutAddArticle.setOnClickListener(v ->
                startActivity(new Intent(this, AddArticleActivity.class))
        );

        // 添加商品
        layoutAddProduct.setOnClickListener(v ->
                startActivity(new Intent(this, AddProductActivity.class))
        );

        // 退出登录
        btnLogout.setOnClickListener(v -> logoutUser());
    }

    private void logoutUser() {
        SharedPreferences sharedPreferences = getSharedPreferences("user_prefs", MODE_PRIVATE);
        sharedPreferences.edit().remove("username").apply();

        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    private void showChangePasswordDialog(String userId) {
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_change_password, null);

         @SuppressLint({"MissingInflatedId", "LocalSuppress", "ResourceType"}) EditText etNewPassword = dialogView.findViewById(R.layout.dialog_change_password);
         @SuppressLint({"MissingInflatedId", "LocalSuppress", "ResourceType"}) EditText etConfirmPassword = dialogView.findViewById(R.layout.dialog_change_password);

        EditText etCurrentPassword = dialogView.findViewById(R.id.etCurrentPassword);
//        EditText etNewPassword = dialogView.findViewById(R.id.etNewPassword);
//        EditText etConfirmPassword = dialogView.findViewById(R.id.etConfirmPassword);


        new AlertDialog.Builder(this)
                .setTitle("修改密码")
                .setView(dialogView)
                .setPositiveButton("确认", (dialog, which) -> {
                    String currentPass = etCurrentPassword.getText().toString();
                    String newPass = etNewPassword.getText().toString();
                    String confirmPass = etConfirmPassword.getText().toString();

                    if (validatePassword(newPass, confirmPass)) {
                        dbHelper.updateUserPassword(Integer.parseInt(userId), newPass);
                        Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private boolean validatePassword(String newPass, String confirmPass) {
        if (newPass.isEmpty() || confirmPass.isEmpty()) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!newPass.equals(confirmPass)) {
            Toast.makeText(this, "两次输入密码不一致", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (newPass.length() < 6) {
            Toast.makeText(this, "密码长度至少6位", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void showDeleteAccountDialog(String userId) {
        new AlertDialog.Builder(this)
                .setTitle("删除账号")
                .setMessage("确定要永久删除此账号吗？")
                .setPositiveButton("删除", (dialog, which) -> {
                    dbHelper.deleteUser(Integer.parseInt(userId));
                    refreshAccountList();
                    Toast.makeText(this, "账号已删除", Toast.LENGTH_SHORT).show();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void refreshAccountList() {
        accountList.clear();
        accountList.addAll(convertUsersToAccounts(dbHelper.getAllUsers()));
        accountAdapter.notifyDataSetChanged();
    }

    private List<Account> convertUsersToAccounts(List<User> users) {
        List<Account> accounts = new ArrayList<>();
        for (User user : users) {
            accounts.add(new Account(
                    String.valueOf(user.getId()),
                    user.getUsername(),
                    "********", // 不显示真实密码
                    user.isAdmin() ? "管理员" : "普通用户"
            ));
        }
        return accounts;
    }

    private boolean checkAdminStatus() {
        SharedPreferences prefs = getSharedPreferences("user_prefs", MODE_PRIVATE);
        String currentUser = prefs.getString("username", "");
        User user = dbHelper.getUser(currentUser);
        return user != null && user.isAdmin();
    }
}